#include "ordermanager.h"
#include "usermanager.h"
#include <QTimer>
#include <QUuid>
#include <QDebug>
#include <algorithm>

namespace RestaurantSystem {

// 静态成员初始化
OrderManager* OrderManager::s_instance = nullptr;
const int OrderManager::DEFAULT_ORDER_TIMEOUT_MINUTES = 30;

OrderManager::OrderManager(QObject* parent)
    : QObject(parent)
    , m_dataManager(nullptr)
    , m_menuManager(nullptr)
    , m_timeoutCheckTimer(new QTimer(this))
    , m_orderTimeoutMinutes(DEFAULT_ORDER_TIMEOUT_MINUTES)
    , m_autoProcessTimeout(true)
    , m_isInitialized(false)
    , m_dataLoaded(false)
{
    // 设置超时检查定时器(每5分钟检查一次)
    m_timeoutCheckTimer->setInterval(5 * 60 * 1000);
    connect(m_timeoutCheckTimer, &QTimer::timeout, this, &OrderManager::onTimeoutCheckTimer);
}

OrderManager::~OrderManager()
{
    if (m_timeoutCheckTimer) {
        m_timeoutCheckTimer->stop();
    }
}

OrderManager& OrderManager::instance()
{
    if (!s_instance) {
        s_instance = new OrderManager();
    }
    return *s_instance;
}

bool OrderManager::initialize()
{
    if (m_isInitialized) {
        return true;
    }
    
    try {
        m_dataManager = &DataManager::instance();
        m_menuManager = &MenuManager::instance();
        
        // 连接菜单管理器的库存变化信号
        connect(m_menuManager, &MenuManager::stockUpdated,
                this, &OrderManager::onStockStatusChanged);
        
        // 加载订单数据
        if (!loadOrderData()) {
            ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                "Failed to load order data", 
                "OrderManager::initialize");
            return false;
        }
        
        // 连接DataManager的外部文件变更信号
        connect(m_dataManager, &DataManager::externalFileChanged,
                this, &OrderManager::onExternalFileChanged);
        
        m_isInitialized = true;
        if (m_autoProcessTimeout) {
            m_timeoutCheckTimer->start();
        }
        

        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::CRITICAL, 
            QString("OrderManager initialization failed: %1").arg(e.what()), 
            "OrderManager::initialize");
        return false;
    }
}

// ========================================================================
// 订单创建和管理
// ========================================================================

QPair<OrderOperationResult, QString> OrderManager::createOrder(const OrderCreateRequest& request)
{
    if (!m_isInitialized) {
        return qMakePair(OrderOperationResult::SYSTEM_ERROR, QString());
    }
    
    // 验证请求数据
    if (!request.isValid()) {
        return qMakePair(OrderOperationResult::INVALID_DATA, QString());
    }
    
    // 验证订单项目
    ValidationResult itemValidation = validateOrderItems(request.items);
    if (!itemValidation.isValid) {
        ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
            QString("Invalid order items: %1").arg(itemValidation.errorMessage), 
            "OrderManager::createOrder");
        return qMakePair(OrderOperationResult::INVALID_DATA, QString());
    }
    
    // 检查库存
    if (!checkStockAvailability(request.items)) {
        return qMakePair(OrderOperationResult::INSUFFICIENT_STOCK, QString());
    }
    
    try {
        // 创建订单
        Order order;
        order.id = generateOrderId();
        order.customerId = request.customerId;
        order.items = request.items;
        order.totalAmount = calculateOrderTotal(request.items);
        order.status = OrderStatus::PENDING;
        order.createdDate = QDateTime::currentDateTime();
        order.paymentMethod = request.paymentMethod;
        
        // 验证完整订单
        ValidationResult orderValidation = validateOrder(order);
        if (!orderValidation.isValid) {
            return qMakePair(OrderOperationResult::INVALID_DATA, QString());
        }
        
        // 先保存订单，再预留库存
        if (m_dataManager->addOrder(order)) {
            // 预留库存
            if (!reserveStock(order)) {
                // 如果预留失败，需要删除已保存的订单
                m_dataManager->deleteOrder(order.id);
                ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
                    "Failed to reserve stock for order", 
                    "OrderManager::createOrder");
                return qMakePair(OrderOperationResult::INSUFFICIENT_STOCK, QString());
            }
            
            // 添加到内存中的订单列表 (使用单独的锁作用域)
            {
                QMutexLocker locker(&m_mutex);
                m_orders.append(order);
            }
            
            emit orderCreated(order);
            
            return qMakePair(OrderOperationResult::SUCCESS, order.id);
        } else {
            releaseStockReservation(order.id);
            return qMakePair(OrderOperationResult::SYSTEM_ERROR, QString());
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during order creation: %1").arg(e.what()), 
            "OrderManager::createOrder");
        return qMakePair(OrderOperationResult::SYSTEM_ERROR, QString());
    }
}

QList<Order> OrderManager::getAllOrders()
{
    QMutexLocker locker(&m_mutex);
    return m_orders;
}

Order OrderManager::getOrderById(const QString& id)
{
    QMutexLocker locker(&m_mutex);
    
    auto it = std::find_if(m_orders.begin(), m_orders.end(),
        [&id](const Order& order) { return order.id == id; });
    
    return (it != m_orders.end()) ? *it : Order();
}

QList<Order> OrderManager::getOrdersByCustomerId(const QString& customerId)
{
    QMutexLocker locker(&m_mutex);
    
    QList<Order> result;
    for (const Order& order : m_orders) {
        if (order.customerId == customerId) {
            result.append(order);
        }
    }
    
    // 按创建时间排序(最新的在前)
    std::sort(result.begin(), result.end(),
        [](const Order& a, const Order& b) {
            return a.createdDate > b.createdDate;
        });
    
    return result;
}

QList<Order> OrderManager::getOrdersByStatus(OrderStatus status)
{
    QMutexLocker locker(&m_mutex);
    
    QList<Order> result;
    for (const Order& order : m_orders) {
        if (order.status == status) {
            result.append(order);
        }
    }
    return result;
}

QList<Order> OrderManager::searchOrders(const OrderSearchCriteria& criteria)
{
    QMutexLocker locker(&m_mutex);
    
    QList<Order> result;
    for (const Order& order : m_orders) {
        if (matchesSearchCriteria(order, criteria)) {
            result.append(order);
        }
    }
    return result;
}

OrderOperationResult OrderManager::cancelOrder(const QString& orderId, const QString& reason)
{
    if (!m_isInitialized) {
        return OrderOperationResult::SYSTEM_ERROR;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_orders.begin(), m_orders.end(),
        [&orderId](const Order& order) { return order.id == orderId; });
    
    if (it == m_orders.end()) {
        return OrderOperationResult::ORDER_NOT_FOUND;
    }
    
    // 检查是否可以取消
    if (!it->canCancel()) {
        return OrderOperationResult::INVALID_STATUS_CHANGE;
    }
    
    try {
        OrderStatus oldStatus = it->status;
        it->status = OrderStatus::CANCELLED;
        it->completedDate = QDateTime::currentDateTime();
        
        // 保存更新
        if (m_dataManager->updateOrder(*it)) {
            // 释放库存预留
            releaseStockReservation(orderId);
            
            emit orderCancelled(orderId, reason);
            emit orderStatusUpdated(orderId, oldStatus, OrderStatus::CANCELLED);
            
            return OrderOperationResult::SUCCESS;
        } else {
            it->status = oldStatus; // 回滚
            return OrderOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during order cancellation: %1").arg(e.what()), 
            "OrderManager::cancelOrder");
        return OrderOperationResult::SYSTEM_ERROR;
    }
}

OrderOperationResult OrderManager::deleteOrder(const QString& orderId)
{
    if (!m_isInitialized) {
        return OrderOperationResult::SYSTEM_ERROR;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_orders.begin(), m_orders.end(),
        [&orderId](const Order& order) { return order.id == orderId; });
    
    if (it == m_orders.end()) {
        return OrderOperationResult::ORDER_NOT_FOUND;
    }
    
    try {
        Order orderToDelete = *it;  // 保存订单副本
        
        // 从数据库删除
        if (m_dataManager->deleteOrder(orderId)) {
            m_orders.erase(it);
            
            // 释放锁后处理库存预留
            locker.unlock();
            releaseStockReservation(orderId);
            
            return OrderOperationResult::SUCCESS;
        } else {
            return OrderOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during order deletion: %1").arg(e.what()), 
            "OrderManager::deleteOrder");
        return OrderOperationResult::SYSTEM_ERROR;
    }
}

// ========================================================================
// 订单状态管理
// ========================================================================

OrderOperationResult OrderManager::updateOrderStatus(const QString& orderId, OrderStatus newStatus)
{
    if (!m_isInitialized) {
        return OrderOperationResult::SYSTEM_ERROR;
    }
    
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_orders.begin(), m_orders.end(),
        [&orderId](const Order& order) { return order.id == orderId; });
    
    if (it == m_orders.end()) {
        return OrderOperationResult::ORDER_NOT_FOUND;
    }
    
    OrderStatus oldStatus = it->status;
    
    // 检查状态变更是否有效
    if (!isValidStatusChange(oldStatus, newStatus)) {
        return OrderOperationResult::INVALID_STATUS_CHANGE;
    }
    
    Order orderCopy = *it;  // 创建副本用于后续处理
    
    try {
        it->status = newStatus;
        if (newStatus == OrderStatus::COMPLETED || newStatus == OrderStatus::CANCELLED) {
            it->completedDate = QDateTime::currentDateTime();
        }
        
        // 保存更新
        if (m_dataManager->updateOrder(*it)) {
            // 在释放锁之前保存需要的信息
            Order updatedOrder = *it;
            
            // 释放锁，然后处理状态变更的副作用
            locker.unlock();
            
            handleStatusChangeEffects(updatedOrder, oldStatus, newStatus);
            
            emit orderStatusUpdated(orderId, oldStatus, newStatus);
            
            if (newStatus == OrderStatus::COMPLETED) {
                emit orderCompleted(orderId);
            }
            
            return OrderOperationResult::SUCCESS;
        } else {
            it->status = oldStatus; // 回滚
            return OrderOperationResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during status update: %1").arg(e.what()), 
            "OrderManager::updateOrderStatus");
        return OrderOperationResult::SYSTEM_ERROR;
    }
}

OrderOperationResult OrderManager::startPreparingOrder(const QString& orderId)
{
    return updateOrderStatus(orderId, OrderStatus::PREPARING);
}

OrderOperationResult OrderManager::completeOrder(const QString& orderId)
{
    // 直接更新订单状态，销量更新会在 handleStatusChangeEffects 中处理
    return updateOrderStatus(orderId, OrderStatus::COMPLETED);
}

bool OrderManager::isValidStatusChange(OrderStatus currentStatus, OrderStatus newStatus)
{
    // 定义有效的状态转换
    switch (currentStatus) {
    case OrderStatus::PENDING:
        return newStatus == OrderStatus::PREPARING || newStatus == OrderStatus::CANCELLED;
        
    case OrderStatus::PREPARING:
        return newStatus == OrderStatus::COMPLETED || newStatus == OrderStatus::CANCELLED;
        
    case OrderStatus::COMPLETED:
    case OrderStatus::CANCELLED:
        return false; // 终态不能再变更
        
    default:
        return false;
    }
}

QList<OrderStatus> OrderManager::getAvailableNextStatuses(OrderStatus currentStatus)
{
    QList<OrderStatus> statuses;
    
    switch (currentStatus) {
    case OrderStatus::PENDING:
        statuses << OrderStatus::PREPARING << OrderStatus::CANCELLED;
        break;
        
    case OrderStatus::PREPARING:
        statuses << OrderStatus::COMPLETED << OrderStatus::CANCELLED;
        break;
        
    case OrderStatus::COMPLETED:
    case OrderStatus::CANCELLED:
        // 终态，无可用状态
        break;
    }
    
    return statuses;
}

// ========================================================================
// 库存管理集成
// ========================================================================

bool OrderManager::checkStockAvailability(const QList<OrderItem>& items)
{
    for (const OrderItem& item : items) {
        if (!m_menuManager->isStockSufficient(item.menuItemId, item.quantity)) {
            MenuItem menuItem = m_menuManager->getMenuItemById(item.menuItemId);
            emit stockInsufficient(item.menuItemId, item.quantity, menuItem.stock);
            return false;
        }
    }
    return true;
}

bool OrderManager::reserveStock(const Order& order)
{
    if (!order.isValid()) {
        LOG_ERROR(QString("订单对象无效，订单ID: %1").arg(order.id), "OrderManager::reserveStock");
        return false;
    }
    
    // 尝试减少库存(预留)
    QList<OrderItem> reservedItems;
    for (const OrderItem& item : order.items) {
        auto result = m_menuManager->decreaseStock(item.menuItemId, item.quantity);
        if (result == MenuOperationResult::SUCCESS) {
            reservedItems.append(item);
        } else {
            LOG_ERROR(QString("库存预留失败：菜品ID=%1, 错误码=%2").arg(item.menuItemId).arg(static_cast<int>(result)), "OrderManager::reserveStock");
            // 回滚已预留的库存
            for (const OrderItem& reservedItem : reservedItems) {
                m_menuManager->increaseStock(reservedItem.menuItemId, reservedItem.quantity);
            }
            return false;
        }
    }
    
    // 记录预留信息
    {
        QMutexLocker locker(&m_mutex);
        m_stockReservations[order.id] = order.items;
    }
    return true;
}

bool OrderManager::releaseStockReservation(const QString& orderId)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_stockReservations.contains(orderId)) {
        return true; // 没有预留，视为成功
    }
    
    QList<OrderItem> reservedItems = m_stockReservations[orderId];
    
    // 恢复库存
    for (const OrderItem& item : reservedItems) {
        m_menuManager->increaseStock(item.menuItemId, item.quantity);
    }
    
    m_stockReservations.remove(orderId);
    return true;
}

bool OrderManager::confirmStockConsumption(const QString& orderId)
{
    QMutexLocker locker(&m_mutex);
    
    if (m_stockReservations.contains(orderId)) {
        QList<OrderItem> items = m_stockReservations[orderId];
        
        // 更新菜品销量
        updateMenuItemSales(items);
        
        // 移除预留记录(库存已实际消耗)
        m_stockReservations.remove(orderId);
        return true;
    }
    
    return false;
}

// ========================================================================
// 订单计算和验证
// ========================================================================

double OrderManager::calculateOrderTotal(const QList<OrderItem>& items)
{
    double total = 0.0;
    for (const OrderItem& item : items) {
        total += item.price * item.quantity;
    }
    return total;
}

ValidationResult OrderManager::validateOrder(const Order& order)
{
    if (order.id.isEmpty()) {
        return ValidationResult(false, "订单ID不能为空");
    }
    
    if (order.customerId.isEmpty()) {
        return ValidationResult(false, "顾客ID不能为空");
    }
    
    if (order.items.isEmpty()) {
        return ValidationResult(false, "订单项目不能为空");
    }
    
    if (order.totalAmount < 0) {
        return ValidationResult(false, "订单金额不能为负数");
    }
    
    // 验证订单项目
    ValidationResult itemsValidation = validateOrderItems(order.items);
    if (!itemsValidation.isValid) {
        return itemsValidation;
    }
    
    // 验证金额计算
    double calculatedTotal = calculateOrderTotal(order.items);
    if (qAbs(order.totalAmount - calculatedTotal) > 0.01) {
        return ValidationResult(false, "订单金额计算错误");
    }
    
    return ValidationResult(true);
}

ValidationResult OrderManager::validateOrderItems(const QList<OrderItem>& items)
{
    for (const OrderItem& item : items) {
        if (!item.isValid()) {
            return ValidationResult(false, "订单项目数据无效");
        }
        
        if (item.quantity <= 0) {
            return ValidationResult(false, "订单项目数量必须大于0");
        }
        
        if (item.price < 0) {
            return ValidationResult(false, "订单项目价格不能为负数");
        }
        
        // 验证菜品是否存在
        MenuItem menuItem = m_menuManager->getMenuItemById(item.menuItemId);
        if (!menuItem.isValid()) {
            return ValidationResult(false, QString("菜品不存在: %1").arg(item.menuItemId));
        }
    }
    
    return ValidationResult(true);
}

bool OrderManager::recalculateOrderTotal(const QString& orderId)
{
    QMutexLocker locker(&m_mutex);
    auto it = std::find_if(m_orders.begin(), m_orders.end(),
        [&orderId](const Order& order) { return order.id == orderId; });
    
    if (it != m_orders.end()) {
        double newTotal = calculateOrderTotal(it->items);
        if (qAbs(it->totalAmount - newTotal) > 0.01) {
            it->totalAmount = newTotal;
            return m_dataManager->updateOrder(*it);
        }
    }
    
    return false;
}

// ========================================================================
// 统计和报表
// ========================================================================

OrderStatistics OrderManager::getOrderStatistics(const QDateTime& startDate, const QDateTime& endDate)
{
    QMutexLocker locker(&m_mutex);
    
    OrderStatistics stats;
    
    for (const Order& order : m_orders) {
        // 日期过滤
        if (startDate.isValid() && order.createdDate < startDate) {
            continue;
        }
        if (endDate.isValid() && order.createdDate > endDate) {
            continue;
        }
        
        stats.totalOrders++;
        
        switch (order.status) {
        case OrderStatus::PENDING:
            stats.pendingOrders++;
            break;
        case OrderStatus::PREPARING:
            stats.preparingOrders++;
            break;
        case OrderStatus::COMPLETED:
            stats.completedOrders++;
            stats.totalRevenue += order.totalAmount;
            break;
        case OrderStatus::CANCELLED:
            stats.cancelledOrders++;
            break;
        }
    }
    
    if (stats.completedOrders > 0) {
        stats.averageOrderValue = stats.totalRevenue / stats.completedOrders;
    }
    
    return stats;
}

OrderStatistics OrderManager::getTodayStatistics()
{
    QDateTime today = QDateTime::currentDateTime();
    QDateTime startOfDay = QDateTime(today.date(), QTime(0, 0, 0));
    QDateTime endOfDay = QDateTime(today.date(), QTime(23, 59, 59));
    
    return getOrderStatistics(startOfDay, endOfDay);
}

QHash<QString, int> OrderManager::getPopularItemsFromOrders(int limit)
{
    QMutexLocker locker(&m_mutex);
    
    QHash<QString, int> itemCounts;
    
    for (const Order& order : m_orders) {
        if (order.status == OrderStatus::COMPLETED) {
            for (const OrderItem& item : order.items) {
                itemCounts[item.menuItemId] += item.quantity;
            }
        }
    }
    
    // 转换为列表并排序
    QList<QPair<QString, int>> sortedItems;
    for (auto it = itemCounts.begin(); it != itemCounts.end(); ++it) {
        sortedItems.append(qMakePair(it.key(), it.value()));
    }
    
    std::sort(sortedItems.begin(), sortedItems.end(),
        [](const QPair<QString, int>& a, const QPair<QString, int>& b) {
            return a.second > b.second;
        });
    
    // 返回前N个
    QHash<QString, int> result;
    int count = qMin(limit, sortedItems.size());
    for (int i = 0; i < count; ++i) {
        result[sortedItems[i].first] = sortedItems[i].second;
    }
    
    return result;
}

OrderStatistics OrderManager::getCustomerOrderStatistics(const QString& customerId)
{
    QMutexLocker locker(&m_mutex);
    
    OrderStatistics stats;
    
    for (const Order& order : m_orders) {
        if (order.customerId != customerId) {
            continue;
        }
        
        stats.totalOrders++;
        
        switch (order.status) {
        case OrderStatus::PENDING:
            stats.pendingOrders++;
            break;
        case OrderStatus::PREPARING:
            stats.preparingOrders++;
            break;
        case OrderStatus::COMPLETED:
            stats.completedOrders++;
            stats.totalRevenue += order.totalAmount;
            break;
        case OrderStatus::CANCELLED:
            stats.cancelledOrders++;
            break;
        }
    }
    
    if (stats.completedOrders > 0) {
        stats.averageOrderValue = stats.totalRevenue / stats.completedOrders;
    }
    
    return stats;
}

// ========================================================================
// 辅助方法
// ========================================================================

QString OrderManager::generateOrderId()
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
    QString uuid = QUuid::createUuid().toString().remove('{').remove('}').remove('-').left(8);
    return QString("ORD_%1_%2").arg(timestamp, uuid);
}

QString OrderManager::getOperationResultMessage(OrderOperationResult result)
{
    switch (result) {
    case OrderOperationResult::SUCCESS:
        return "操作成功";
    case OrderOperationResult::ORDER_NOT_FOUND:
        return "订单不存在";
    case OrderOperationResult::INVALID_DATA:
        return "数据无效";
    case OrderOperationResult::INVALID_STATUS_CHANGE:
        return "状态变更无效";
    case OrderOperationResult::INSUFFICIENT_STOCK:
        return "库存不足";
    case OrderOperationResult::PERMISSION_DENIED:
        return "权限不足";
    case OrderOperationResult::SYSTEM_ERROR:
        return "系统错误";
    default:
        return "未知错误";
    }
}

QString OrderManager::formatOrderSummary(const Order& order)
{
    return QString("订单 %1 - %2项商品 - 总计 ¥%3 - %4")
        .arg(order.id.right(8))
        .arg(order.items.size())
        .arg(order.totalAmount, 0, 'f', 2)
        .arg(getStatusDisplayText(order.status));
}

QString OrderManager::getStatusDisplayText(OrderStatus status)
{
    switch (status) {
    case OrderStatus::PENDING:
        return "待处理";
    case OrderStatus::PREPARING:
        return "制作中";
    case OrderStatus::COMPLETED:
        return "已完成";
    case OrderStatus::CANCELLED:
        return "已取消";
    default:
        return "未知状态";
    }
}

// ========================================================================
// 公共槽函数
// ========================================================================

void OrderManager::refreshOrderData()
{
    if (loadOrderData()) {

    }
}

void OrderManager::processTimeoutOrders()
{
    if (!m_autoProcessTimeout) {
        return;
    }
    
    QMutexLocker locker(&m_mutex);
    QDateTime timeoutThreshold = QDateTime::currentDateTime().addSecs(-m_orderTimeoutMinutes * 60);
    
    for (Order& order : m_orders) {
        if (order.status == OrderStatus::PENDING && order.createdDate < timeoutThreshold) {
            // 自动取消超时的待处理订单
            order.status = OrderStatus::CANCELLED;
            order.completedDate = QDateTime::currentDateTime();
            
            if (m_dataManager->updateOrder(order)) {
                releaseStockReservation(order.id);
                emit orderCancelled(order.id, "订单超时自动取消");
            }
        }
    }
}

// ========================================================================
// 私有槽函数
// ========================================================================

void OrderManager::onTimeoutCheckTimer()
{
    processTimeoutOrders();
}

void OrderManager::onStockStatusChanged(const QString& itemId, int oldStock, int newStock)
{
    Q_UNUSED(itemId)
    Q_UNUSED(oldStock)
    
    // 检查是否有等待该菜品的订单
    if (newStock > 0) {
        // 库存恢复，可能可以处理一些等待的订单
        // 这里可以实现更复杂的逻辑
    }
}

void OrderManager::onExternalFileChanged(DataType dataType, const QString& /*filePath*/)
{
    // 当检测到外部文件变更时，如果是订单数据变更，重新加载缓存
    if (dataType == DataType::ORDERS) {
        // 延迟重新加载，确保文件写入完成
        QTimer::singleShot(100, this, [this]() {
            if (loadOrderData()) {
                // 发射信号通知UI更新
                emit ordersChanged();
            }
        });
    }
}

// ========================================================================
// 私有方法
// ========================================================================

bool OrderManager::loadOrderData()
{
    try {
        QMutexLocker locker(&m_mutex);
        
        m_orders = m_dataManager->getAllOrders();
        m_dataLoaded = true;
        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Failed to load order data: %1").arg(e.what()), 
            "OrderManager::loadOrderData");
        return false;
    }
}

bool OrderManager::saveOrderData()
{
    try {
        QMutexLocker locker(&m_mutex);
        
        for (const Order& order : m_orders) {
            m_dataManager->updateOrder(order);
        }
        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Failed to save order data: %1").arg(e.what()), 
            "OrderManager::saveOrderData");
        return false;
    }
}

bool OrderManager::matchesSearchCriteria(const Order& order, const OrderSearchCriteria& criteria)
{
    // 顾客ID过滤
    if (!criteria.customerId.isEmpty() && order.customerId != criteria.customerId) {
        return false;
    }
    
    // 顾客名过滤
    if (!criteria.customerName.isEmpty()) {
        // 根据顾客ID获取顾客名
        RestaurantSystem::UserManager& userManager = RestaurantSystem::UserManager::instance();
        Customer customer = userManager.getUserById(order.customerId);
        if (customer.username.isEmpty() || 
            !customer.username.toLower().contains(criteria.customerName.toLower())) {
            return false;
        }
    }
    
    // 状态过滤
    if (criteria.status != static_cast<OrderStatus>(-1) && order.status != criteria.status) {
        return false;
    }
    
    // 日期范围
    if (criteria.startDate.isValid() && order.createdDate < criteria.startDate) {
        return false;
    }
    
    if (criteria.endDate.isValid() && order.createdDate > criteria.endDate) {
        return false;
    }
    
    // 金额范围
    if (criteria.minAmount >= 0 && order.totalAmount < criteria.minAmount) {
        return false;
    }
    
    if (criteria.maxAmount >= 0 && order.totalAmount > criteria.maxAmount) {
        return false;
    }
    
    // 关键词搜索
    if (!criteria.keyword.isEmpty()) {
        QString keyword = criteria.keyword.toLower();
        bool found = false;
        
        // 搜索订单ID
        if (order.id.toLower().contains(keyword)) {
            found = true;
        }
        
        // 搜索菜品名称
        if (!found) {
            for (const OrderItem& item : order.items) {
                if (item.menuItemName.toLower().contains(keyword)) {
                    found = true;
                    break;
                }
            }
        }
        
        if (!found) {
            return false;
        }
    }
    
    return true;
}

void OrderManager::updateMenuItemSales(const QList<OrderItem>& items)
{
    for (const OrderItem& item : items) {
        m_menuManager->updateSalesCount(item.menuItemId, item.quantity);
    }
}

void OrderManager::handleStatusChangeEffects(const Order& order, OrderStatus oldStatus, OrderStatus newStatus)
{
    Q_UNUSED(oldStatus)
    
    switch (newStatus) {
    case OrderStatus::COMPLETED:
        {
            // 订单完成：确认库存消耗，更新销量
            bool hasReservation = confirmStockConsumption(order.id);
            
            // 如果没有库存预留记录，直接更新销量
            if (!hasReservation) {
                updateMenuItemSales(order.items);
            }
        }
        break;
        
    case OrderStatus::CANCELLED:
        // 订单取消：释放库存预留
        releaseStockReservation(order.id);
        break;
        
    case OrderStatus::PENDING:
    case OrderStatus::PREPARING:
    default:
        // 其他状态变更无特殊处理
        break;
    }
}

} // namespace RestaurantSystem
